import { Address, fromNano, toNano, TonClient } from "@ton/ton"
import { useTonAddress } from "@tonconnect/ui-react";
import { useEffect, useState } from "react"

// 初始化TON客户端（测试网）
const tonClient = new TonClient({
    endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
})

export const Balance = ()=>{

    const [balance, setBalance] = useState<string>('0');
    const address = useTonAddress()

    // 获取钱包余额
    const getBalance = async () => {
        if(!address) return
        console.log('tonClient----------')
        console.log(tonClient)
        console.log('address-------')
        console.log(address)
        console.log('Address.parse(address)---')
        console.log(Address.parse(address))
        const balance = await tonClient.getBalance(Address.parse(address))
        console.log('balance------')
        console.log(balance,toNano(balance),fromNano(balance))
        setBalance(fromNano(balance))
    }

    useEffect(()=>{
        getBalance()
    },[address])

    return <div>
        <br />
        <p>获取余额------------------- </p>
        <p>TON空间余额: { balance }Ton</p>
        
    </div>
}